﻿using System;
using TMPro;
using UnityEngine;
using XLua;
using Yoozoo.Framework.Core;
using Yoozoo.Framework.Managers;
using Yoozoo.UI.YGUI;

namespace Yoozoo.Gameplay.Managers
{
    public class LocalizationManager : Singleton<LocalizationManager>
    {
        private LuaTable m_langTable;

        private LuaTable m_fontTable;
        private LuaFunction getFontFunction;
        private LuaFunction getTextMeshProFontFunction;
        private LuaFunction getLangTextFunction;

        public void Initialize()
        {
            m_langTable = LuaManager.GetTable("L_LangUtils");
            getLangTextFunction = m_langTable?.Get<LuaFunction>("getLangText");

            m_fontTable = LuaManager.GetTable("L_FontUtils");
            getFontFunction = m_fontTable?.Get<LuaFunction>("getFont");
            getTextMeshProFontFunction = m_fontTable?.Get<LuaFunction>("getTextMeshProFont");
            if (getLangTextFunction != null)
            {
                YText.localizationProvider = GetLocalizationText;
            }

            if (getFontFunction != null)
            {
                //YTextStyle.localizationProvider = GetLocalizationFont;
            }

            if (getTextMeshProFontFunction != null)
            {
                //TextMeshProLocalizationProvider.localizationProvider = GetLocalizationTextMeshProFont;
                //GpuHudFacade.localizationProvider = GetLocalizationTextMeshProFont;
            }
            
        }

        private void GetLocalizationFont(string oldFontName, Action<Font> setNewFont)
        {
            var font = getFontFunction?.Func<LuaTable, string, Font>(m_fontTable, oldFontName);

            if (font != null)
                setNewFont?.Invoke(font);
        }

        private void GetLocalizationTextMeshProFont(string oldFontName, Action<TMP_FontAsset> setNewFont)
        {
            var font = getTextMeshProFontFunction?.Func<LuaTable, string, TMP_FontAsset>(m_fontTable, oldFontName);

            if (font != null)
                setNewFont?.Invoke(font);
        }

        private string GetLocalizationText(string localizationKey)
        {
            return getLangTextFunction?.Func<int, string, string>(0, localizationKey);
        }

        public string GetLocalizationTextPublic(string localizationKey)
        {
            try
            {
                return getLangTextFunction?.Func<int, string, string>(0, localizationKey);
            }
            catch
            {
                return "";
            }
        }
    }
}
